import { Alert, Checkbox, message, Button } from "antd";
import { useEffect, useMemo, useCallback, useState } from "react";
import CommonTable from "@/components/CommonTable";
import CommonLoading from "@/components/CommonLoading";
import CommonModal from "@/components/CommonModal";
import { queryLabelTypeEnumList, labelSort } from "../../service";

/** 列表字段设置 */
function EditColumnsCode(props) {
	const { handleOk, handleCancel } = props;
	const [loading, setLoading] = useState(false);
	const [showList, setShowList] = useState([]); //更改之后的数据
	const [isOk, setIsOk] = useState(false);
	const [open, setOpen] = useState(false);

	useEffect(() => {
		setOpen(true);
	}, []);

	useEffect(() => {
		if (open) {
			getListLabelSort();
		}
	}, [open]);

	//获取标签类型
	const getListLabelSort = async () => {
		setLoading(true);
		const { data = [], success } = await queryLabelTypeEnumList();
		if (success) {
			setShowList(data);
		}
		setLoading(false);
	};

	//保存标签排序
	const handleLabelSort = async () => {
		setLoading(true);
		const arr = [];
		showList.forEach((item, index) => {
			arr.push({
				sort: index + 1,
				labelType: item.labelType
			});
		});
		const { success } = await labelSort(arr);
		if (success) {
			setIsOk(true);
			setOpen(false);
		}
		setLoading(false);
	};

	const onOk = async () => {
		handleLabelSort();
	};

	const onCancel = () => {
		setOpen(false);
	};

	const afterClose = () => {
		if (isOk) {
			handleOk();
		} else {
			handleCancel();
		}
	};

	const columns = [
		{
			title: "标签排序",
			dataIndex: "templateName"
		}
	];

	const TableProps = {
		data: showList,
		size: "small",
		columns,
		rowKey: "id",
		bordered: true,
		isSortData: true,
		scroll: {
			y: "45vh"
		},
		onDragEnd(val) {
			setShowList(val);
		}
	};

	return (
		<CommonModal
			width="450px"
			title="标签排序"
			open={open}
			onOk={onOk}
			onCancel={onCancel}
			afterClose={afterClose}
			footer={
				<>
					<Button onClick={onCancel}>取消</Button>
					<Button type="primary" onClick={onOk}>
						保存
					</Button>
				</>
			}
		>
			<CommonTable {...TableProps} />
			<CommonLoading loading={loading} />
		</CommonModal>
	);
}

export default EditColumnsCode;
